package com.manage;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;

import android.content.Intent;
import android.graphics.Color;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.ViewGroup.MarginLayoutParams;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView;

import com.manage.adapter.OrderAdapter;
import com.manage.base.BaseActivity;
import com.manage.http.AsyncHttpPost;
import com.manage.http.DefaultThreadPool;
import com.manage.http.RequestException;
import com.manage.http.RequestParameter;
import com.manage.http.RequestResultCallback;
import com.manage.model.Order;
import com.manage.model.OrderItem;
import com.manage.sharedpreferences.SPConfig;
import com.manage.util.ToastUtils;
import com.manage.widgets.CustomDialog;
import com.manage.widgets.DialogActionListener;
import com.manage.widgets.RemarkDialog;

/**
 * 订单详情 2012-6-1
 * 
 * @author liyoro@163.com
 * 
 */
public class OrderDetailActivity extends BaseActivity implements
		OnItemClickListener, OnClickListener {

	private static String TAG = "OrderDetailActivity";
	public static String SERORDERLIST = "orderlist";
	
	private Order order = null;

	private ArrayList<OrderItem> orderList = new ArrayList();
	private OrderAdapter orderAdapter = null;

	// top
	private ListView caipinList = null;

	// center
	private TextView tvPrice = null;
	private TextView tvOrderAdditional = null;
	private Button btnAcceptOrder = null;

	// bottom
	private TextView tvClientName = null;
	private TextView tvPhoneNumber = null;
	private TextView tvClientcBuinding = null;
	private TextView tvClientAddress = null;
	private TextView tvClientOrderTime = null;
	private Button btnCancelOrder = null;
	private Button btnModifyOrder = null;
	
	private CustomDialog acceptOrderDialog = null;
	private CustomDialog cancelOrderDialog = null;
	
	private ImageView ivPhoneCall = null;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		this.setContentView(R.layout.activity_manage_order_details);
		initDatas();

		setListViewHeightBasedOnChildren(caipinList);
	}

	@Override
	public String getLeftBtnName() {
		return "返回";
	}

	@Override
	public String getTitleName() {
		return "订单详情";
	}

	@Override
	public boolean showButton() {
		return true;
	}

	@Override
	public void initView() {
		caipinList = (ListView) findViewById(R.id.listview1);
		
		orderAdapter = new OrderAdapter(OrderDetailActivity.this);
		caipinList.setAdapter(orderAdapter);

		tvPrice = (TextView) findViewById(R.id.total_price);
		tvOrderAdditional = (TextView) findViewById(R.id.order_additional);
		btnAcceptOrder = (Button) findViewById(R.id.btn_accept_order);
		btnAcceptOrder.setOnClickListener(this);

		tvClientName = (TextView) findViewById(R.id.client_name);
		tvPhoneNumber = (TextView) findViewById(R.id.phone_number);
		tvClientcBuinding = (TextView) findViewById(R.id.client_buinding);
		tvClientAddress = (TextView) findViewById(R.id.client_address);
		tvClientOrderTime = (TextView) findViewById(R.id.order_time);
		btnCancelOrder = (Button) findViewById(R.id.btn_cancel_order);
		btnModifyOrder = (Button) findViewById(R.id.btn_modify_order);
		btnCancelOrder.setOnClickListener(this);
		btnModifyOrder.setOnClickListener(this);

		ivPhoneCall = (ImageView)findViewById(R.id.iv_call);
		ivPhoneCall.setOnClickListener(this);
	}

	@Override
	public void initDatas() {
		order =  (Order)getIntent().getSerializableExtra(ManageAcceptedActivity.SER_KEY);
		
		if(order != null) {
			tvOrderAdditional.setText(order.getClientAddition());
			
			/**
			 * 如果用户有做备注，变为链接，并且可以点击查看
			 */
			if(order.getRemark() != "") {
				tvClientName.setTextColor(getResources().getColor(R.color.blue));
				tvClientName.setText(Html.fromHtml("<u>" + order.getClientName() + "</u>"));
				
				tvClientName.setOnClickListener(new View.OnClickListener() {
					
					@Override
					public void onClick(View v) {
						RemarkDialog remarkDialog = new RemarkDialog(OrderDetailActivity.this, order.getClientName(), order.getPhoneNumber());
						remarkDialog.addRemark(order.getRemark());
						remarkDialog.show();
					}
				});
			} else {
				tvClientName.setText(order.getClientName());
			}
			
			tvPhoneNumber.setText(order.getPhoneNumber());
			tvPhoneNumber.setText(Html.fromHtml("<u>" + order.getPhoneNumber() + "</u>"));
			
			tvPhoneNumber.setOnClickListener(new View.OnClickListener() {
				
				@Override
				public void onClick(View v) {
					Intent telIntent = new Intent(  
					                Intent.ACTION_CALL, Uri.parse("tel:"+ order.getPhoneNumber()));
					startActivity(telIntent);
				} 
			});
			
			tvClientcBuinding.setText(order.getClientBuilding());
			tvClientAddress.setText(order.getClientAddress());
			tvClientOrderTime.setText(order.getOrderTime());
			
			orderList = order.getDishes();
			
			orderAdapter.setValue(orderList);
		}
		tvPrice.setText(orderAdapter.getTotalPrice());
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {

	}

	@Override
	public void onClick(View v) {
		int id = v.getId();
		switch (id) {
		case R.id.btn_accept_order:
			String btnStr = btnAcceptOrder.getText().toString();
			if(btnStr.endsWith("受理订单")) {
				acceptOrder();
			} else { //新增餐品
				addOrder(orderList);
			}
			break;
		case R.id.btn_cancel_order:
			cancelOrder();
			break;
		case R.id.btn_modify_order:
			modifyOrder();
			break;
		case R.id.iv_call:
			Intent telIntent = new Intent(  
	                Intent.ACTION_CALL, Uri.parse("tel:"+ order.getPhoneNumber()));
			startActivity(telIntent);
			break;
		default:
			break;
		}
	}

	/**
	 * 解决ScrollView与ListView共存 获取并设置ListView高度的方法
	 * 
	 * @param listView
	 */
	public void setListViewHeightBasedOnChildren(ListView listView) {
		ListAdapter listAdapter = listView.getAdapter();
		if (listAdapter == null) {
			return;
		}

		int totalHeight = 0;
		for (int i = 0; i < listAdapter.getCount(); i++) {
			View listItem = listAdapter.getView(i, null, listView);
			listItem.measure(0, 0);
			totalHeight += listItem.getMeasuredHeight();
		}

		ViewGroup.LayoutParams params = listView.getLayoutParams();
		params.height = totalHeight + (listView.getDividerHeight() * (listAdapter.getCount() - 1));
		((MarginLayoutParams) params).setMargins(10, 10, 10, 10);
		
		params.height += 30;
		listView.setLayoutParams(params);
	}

	/**
	 * "受理订单"按钮的点击处理
	 */
	public void acceptOrder() {
		if(btnAcceptOrder.getText().equals("受理订单")) {
			acceptOrderDialog = new CustomDialog(this, "您确定要受理此订单吗？", false);
			acceptOrderDialog.setDialogConfirmAction(new DialogActionListener() {
				
				@Override
				public void confirmAction() {
					Log.i(TAG, "confirmAction");
					acceptOrderDialog.dismiss();
					Log.i(TAG, "aaaaaaaaaaaaaaaaaaa:" + order.getOrderID());
					modifyOrder(order.getOrderID(), "2", "");
				}

				@Override
				public void confirmAction(String paramString, String paramString2) {
					// TODO Auto-generated method stub
					
				}
			});
			acceptOrderDialog.show();
		} else {
			
		}
	}
	
	/**
	 * “新增餐品”按钮的点击处理
	 */
	public void addOrder(ArrayList<OrderItem> orderList) {
		Intent mIntent = new Intent();
		mIntent.setClass(OrderDetailActivity.this, ModifyOrderActivity.class);
		
		Bundle mBundle = new Bundle();
		mBundle.putSerializable(SERORDERLIST, orderList);
		
		mIntent.putExtras(mBundle);
		
		startActivityForResult(mIntent, ADDORDERMENUS);
//		startActivity(mIntent);
	}
	
	/**
	 * “取消订单"按钮的点击处理
	 */
	public void cancelOrder() {
		cancelOrderDialog = new CustomDialog(this, "您确定要取消此订单吗？", true);
		cancelOrderDialog.setDialogConfirmAction(new DialogActionListener() {
			
			@Override
			public void confirmAction() {
			}

			@Override
			public void confirmAction(String paramString, String paramString2) {
				cancelOrderDialog.dismiss();
				modifyOrder(order.getOrderID(), "5", paramString);
			}
		});
		cancelOrderDialog.show();
	}
	
	/**
	 * ”修改订单“按钮的点击处理
	 */
	public void modifyOrder() {
		if(btnModifyOrder.getText().equals("修改订单")) {
			orderAdapter.showEditButton(View.VISIBLE);
			btnAcceptOrder.setText("新增餐品");
			btnAcceptOrder.setTextColor(Color.BLUE);
			btnModifyOrder.setText("提交订单");
			btnModifyOrder.setTextColor(Color.BLUE);
		} else {
			orderAdapter.showEditButton(View.GONE);
			btnAcceptOrder.setText("受理订单");
			btnAcceptOrder.setTextColor(Color.BLACK);
			btnModifyOrder.setText("修改订单");
			btnModifyOrder.setTextColor(Color.BLACK);
			
			tvPrice.setText(orderAdapter.getTotalPrice());
		}
	}
	
	@SuppressWarnings("unchecked")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		switch (requestCode) {
		case ADDORDERMENUS:
			if(data != null) {
				orderList = (ArrayList<OrderItem>)data.getSerializableExtra(SERORDERLIST);
//				Log.i(TAG, "btn_submit:"+orderListParent.size());
				orderAdapter.setClear(true);
				orderAdapter.setValue(orderList);
				tvPrice.setText(orderAdapter.getTotalPrice());

				setListViewHeightBasedOnChildren(caipinList);
			}
			break;
		default:
			break;
		}
	}
	
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) { 
			switch(msg.what) {
			case CANCELSUCCESS:
				Log.i(TAG, "SUCCESS");
				ToastUtils.show(OrderDetailActivity.this, "订单已经成功取消！", true);
				OrderDetailActivity.this.finish();
				break;
			case CANCELFAIL: //
				ToastUtils.show(OrderDetailActivity.this, "获取数据失败，请稍侯重试！", true);
				break;
			case ACCEPTSUCCESS:
				ToastUtils.show(OrderDetailActivity.this, "成功受理订单！", true);
				OrderDetailActivity.this.finish();
				break;
			case ACCEPTFAIL:
				ToastUtils.show(OrderDetailActivity.this, "受理订单失败，请稍侯重试！", true);
				break;
			default:
				break;
				
			}
		}
	};
	
	/**
	 * 
	 * @param paramString1 shopid商店id
	 * @param paramString2 status 修改订单状态，有1: 待受理，2：待配送，3：待入账，4：已入账,5:已取消
	 * @param paramString3 feedback 用户反馈
	 */
	private void modifyOrder(String paramString1, final String paramString2, String paramString3) {
		String token = sp.getString(SPConfig.ACCESSTOKEN, "0");
		
		List<RequestParameter> parameterList = new ArrayList<RequestParameter>();
		parameterList.add(new RequestParameter("token", token));
		parameterList.add(new RequestParameter("orderid", paramString1));
		parameterList.add(new RequestParameter("status", paramString2));
		parameterList.add(new RequestParameter("feedback", paramString3));
		
		AsyncHttpPost httpost = new AsyncHttpPost(null, MODIFYORDERURL, parameterList,
				new RequestResultCallback(){

				@Override
				public void onSuccess(Object o) {
					Log.i("HttpPostExample", "HttpPostExample  request  onSuccess result :"+((String)o).toString());
						
					try {
						JSONObject jsonTemp = new JSONObject(((String)o).toString());
						boolean res = jsonTemp.getBoolean("status_return");
						Log.i(TAG, "res:"+res);
						
						if(res == true && paramString2 == "5") {
							handler.sendEmptyMessage(CANCELSUCCESS);
						} 
						else if(res == false && paramString2 == "5"){
							handler.sendEmptyMessage(CANCELFAIL);  
						} 
						else if(res == true && paramString2 == "2") {
							handler.sendEmptyMessage(ACCEPTSUCCESS);
						}
						else if(res == false && paramString2 == "2") {
							handler.sendEmptyMessage(ACCEPTFAIL);
						}
					} catch (JSONException e) {
						e.printStackTrace();
					}
				}
					
				@Override
				public void onFail(Exception e) {
					Log.i("HttpPostExample", "HttpPostExample  request   onFail :"+((RequestException)e).getMessage());
						
			        handler.sendEmptyMessage(CANCELFAIL);  //向Handler发送消息
				}
		});
		
		DefaultThreadPool.getInstance().execute(httpost);
	 
		this.requestList.add(httpost);
	}
}
